package com.uchedao.vehicledetection.adapter;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.utils.L;
import com.uchedao.mybaselibrary.view.dialog_for_ios.ZAlertDialog;
import com.uchedao.vehicledetection.R;
import com.uchedao.vehicledetection.global.GlobalInfo;
import com.uchedao.vehicledetection.model.Detection;
import com.uchedao.vehicledetection.view.widget.stickylistheaders.StickyListHeadersAdapter;

import java.util.ArrayList;

public class EngineManualAdapter extends BaseAdapter implements StickyListHeadersAdapter {
    /**
     * 监听接口
     *
     * @author "叶晋"
     */
    public interface EngineManualAdapterListener {
        /**
         * 值结果
         *
         * @param position
         * @param value
         */
        public void onResult(int position, String value);

        /**
         * 单选结果
         *
         * @param position
         * @param value
         */
        public void onResult(int position, int value);

        /**
         * 多选结果
         *
         * @param position
         * @param value
         */
        public void onResult(int position, ArrayList<Integer> value);

    }

    private ArrayList<Detection> array;

    private LayoutInflater inflater;

    private Context mContext;

    // 当前索引
    private int index;

    private EngineManualAdapterListener listener;

    private int resultTvWidth;

    // 多选项的值
    private boolean[] checkedItems;

    private int minWidth = 0;

    public void setMinWidth(int minWidth) {
        this.minWidth = minWidth;
        notifyDataSetChanged();
    }

    public EngineManualAdapter(Context context, ArrayList<Detection> list, EngineManualAdapterListener adapterListener) {
        inflater = LayoutInflater.from(context);
        array = list;
        mContext = context;
        listener = adapterListener;
    }

    /**
     * 设置默认值，防止用户未选择时，没有值
     */
    public void setDefaultValue() {
        if (listener == null || array == null)
            return;
        L.w("setDefaultValue " + array.size());
        for (int i = 0; i < array.size(); i++) {
            Detection detection = array.get(i);

            // 二选一
            if ((detection.getValueType() & Detection.TYPE_TWO_SELECT) != 0) {
                L.w("Detection.TYPE_TWO_SELECT");
                listener.onResult(i, detection.getValue());

                // 三选一
            } else if ((detection.getValueType() & Detection.TYPE_THREE_SELECT) != 0) {
                L.w("Detection.TYPE_THREE_SELECT");
                listener.onResult(i, detection.getValue());

                // 多选一
            } else if ((detection.getValueType() & Detection.TYPE_SINGLE_CHOICE) != 0) {
                L.w("Detection.TYPE_SINGLE_CHOICE");
                listener.onResult(i, detection.getValue());

                // 多选
            } else if ((detection.getValueType() & Detection.TYPE_MULTIPLE) != 0) {
                L.w("Detection.TYPE_MULTIPLE");
                ArrayList<Integer> ints = detection.getValues();
                if (ints.size() == 0)
                    ints.add(0);
                listener.onResult(i, ints);
            }
        }
    }

    @Override
    public int getCount() {
        if (array == null)
            return 0;
        return array.size();
    }

    @Override
    public Object getItem(int position) {
        if (array == null)
            return 0;
        return array.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    class ViewHolder {
        TextView text;
        LinearLayout inputLayout;
        ImageView star;
        EditText edit;
        TextView unit;
        TextView result;
    }

    private class CustomTextWatcher implements TextWatcher {

        EditText et;
        TextView tv;
        ImageView star;

        public CustomTextWatcher(EditText et, TextView tv, ImageView star) {
            this.et = et;
            this.tv = tv;
            this.star = star;
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            L.i("afterTextChanged start");
            // EditText et = (EditText) s;
            if (!et.hasFocus())
                et.requestFocus();
            int i = (Integer) et.getTag();

            Detection detection = array.get(i);
            detection.setStrValue(s.toString());
            // notifyDataSetChanged();
            listener.onResult(i, s.toString());

            String[] values = GlobalInfo.resources.getStringArray(detection.getResId());

//            if ("分贝".equals(detection.getKey())) {
//                try {
//                    int k = Integer.parseInt(detection.getStrValue());
//                    if (k > 85) {
//                        tv.setText(values[1]);
//                        tv.setBackgroundResource(R.color.deep_red);
//                        tv.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.ic_red_cross, 0, 0, 0);
//
//                        return;
//                    }
//                } catch (NumberFormatException e) {
//                }
//                tv.setText(values[0]);
//                tv.setBackgroundResource(R.color.deep_green);
//                tv.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.ic_blue_yes, 0, 0, 0);
//
//
//            } else
            if ("mm".equals(detection.getKey())) {

                try {
                    float k = Float.parseFloat(detection.getStrValue());
                    if (k <= 1.65) {
                        tv.setText(values[1]);
                        tv.setBackgroundResource(R.color.deep_red);
                        tv.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.ic_red_cross, 0, 0, 0);

                        return;
                    }
                } catch (NumberFormatException e) {
                }
                tv.setText(values[0]);
                tv.setBackgroundResource(R.color.deep_green);
                tv.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.ic_blue_yes, 0, 0, 0);


            }
//            else if ("°C".equals(detection.getKey())) {
//                try {
//                    int k = Integer.parseInt(detection.getStrValue());
//                    if (k > 16) {
//                        tv.setText(values[1]);
//                        tv.setBackgroundResource(R.color.deep_red);
//                        tv.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.ic_red_cross, 0, 0, 0);
//
//                        return;
//                    }
//                } catch (NumberFormatException e) {
//                }
//                tv.setText(values[0]);
//                tv.setBackgroundResource(R.color.deep_green);
//                tv.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.ic_blue_yes, 0, 0, 0);
//
//
//            }

            if (TextUtils.isEmpty(detection.getStrValue())) {
                star.setVisibility(View.VISIBLE);
            } else {
                star.setVisibility(View.INVISIBLE);
            }

            L.i("afterTextChanged end");
        }
    }

    ;

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolder viewHolder;
        if (convertView == null) {
            viewHolder = new ViewHolder();
            convertView = inflater.inflate(R.layout.item_detection, parent, false);
            convertView.setTag(viewHolder);
            viewHolder.text = (TextView) convertView.findViewById(R.id.subject_tv);
            viewHolder.inputLayout = (LinearLayout) convertView.findViewById(R.id.input_result_layout);
            viewHolder.star = (ImageView) convertView.findViewById(R.id.input_tip_iv);
            viewHolder.edit = (EditText) convertView.findViewById(R.id.input_result_et);
            viewHolder.unit = (TextView) convertView.findViewById(R.id.unit_tv);
            viewHolder.result = (TextView) convertView.findViewById(R.id.detection_result_tv);
//            viewHolder.result.setMinWidth(resultTvWidth);
            if (minWidth > 0) {
                viewHolder.result.setActivated(true);
                viewHolder.result.setMinWidth(minWidth);
            }

            viewHolder.edit.addTextChangedListener(new CustomTextWatcher(viewHolder.edit, viewHolder.result,
                    viewHolder.star));

        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        Detection detection = array.get(position);
        viewHolder.text.setText(detection.getText());
        viewHolder.result.setTag(position);
        // 输入框
        if ((detection.getValueType() & Detection.TYPE_INPUT) != 0) {
            viewHolder.inputLayout.setVisibility(View.VISIBLE);
            viewHolder.unit.setText(detection.getKey());
            viewHolder.edit.setTag(position);
            viewHolder.edit.setText(detection.getStrValue());

        } else {
            viewHolder.inputLayout.setVisibility(View.GONE);
        }
        // 设置值
        setResult(detection, viewHolder.result);

        if (detection.getText().equals("空调（出风温度）")||detection.getText().equals("噪音检查")) {
            viewHolder.inputLayout.setVisibility(View.GONE);

        }
        return convertView;
    }

    /**
     * 单选监听
     */
    private OnClickListener singleChoiceListener = new OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            Detection detection = array.get(index);

            detection.setValue(which);
            notifyDataSetChanged();
            if (listener != null)
                listener.onResult(index, which);
        }
    };

    /**
     * 显示单选对话框
     *
     * @param detection
     * @param listener
     */
    private void showAlertSingleChoiceDialog(Detection detection, OnClickListener listener) {
        AlertDialog alert = new ZAlertDialog.Builder(mContext).setTitle(detection.getText())
                .setItems(detection.getResId(), listener).create();
        alert.show();
    }

    /**
     * 只能单选的多选值
     *
     * @param value
     * @return
     */
    private boolean multipleValueOnlyRadio(String value) {
        return "正常".equals(value) || "无".equals(value);
    }

    /**
     * 多选监听
     */
    private DialogInterface.OnMultiChoiceClickListener multipleChoiceListener = new DialogInterface.OnMultiChoiceClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which, boolean isChecked) {

            Detection detection = array.get(index);
            ListView listView = ((AlertDialog) dialog).getListView();

            // 取消选择
            if (!isChecked) {
                // 当选中的数量小于1时
                if (listView.getCheckedItemCount() == 0) {
                    listView.setItemChecked(which, true);
                    checkedItems[which] = true;
                    Toast.makeText(mContext, R.string.at_least_choice_one, Toast.LENGTH_LONG).show();
                }
                return;

            }

            String[] values = GlobalInfo.resources.getStringArray(detection.getResId());

            // 若该选项只能单选
            if (multipleValueOnlyRadio(values[which])) {
                // 除此项外，其余值取消选择
                for (int i = 0; i < values.length; i++) {
                    listView.setItemChecked(i, i == which);
                    checkedItems[i] = (i == which);
                }

                // 若该选项能多选
            } else {

                for (int i = 0; i < values.length; i++) {
                    // 其余单选项取消选择
                    if (multipleValueOnlyRadio(values[i])) {
                        listView.setItemChecked(i, false);
                        checkedItems[i] = false;
                    }
                }
            }

        }
    };

    /**
     * 显示多选对话框
     *
     * @param detection
     * @param onMultiChoiceClickListener
     */
    private void showAlertMultipleChoiceDialog(Detection detection,
                                               DialogInterface.OnMultiChoiceClickListener onMultiChoiceClickListener) {
        ArrayList<Integer> ints = detection.getValues();
        int size = GlobalInfo.resources.getStringArray(detection.getResId()).length;
        checkedItems = new boolean[size];
        for (int i : ints)
            checkedItems[i] = true;

        OnClickListener okClickListener = new OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                Detection detection = array.get(index);

                ArrayList<Integer> ints = new ArrayList<Integer>();
                for (int i = 0; i < checkedItems.length; i++) {
                    if (checkedItems[i])
                        ints.add(i);
                }
                detection.setValues(ints);
                notifyDataSetChanged();

                if (listener != null)
                    listener.onResult(index, ints);

            }
        };
        new AlertDialog.Builder(mContext).setTitle(detection.getText())
                .setMultiChoiceItems(detection.getResId(), checkedItems, onMultiChoiceClickListener)
                .setPositiveButton(R.string.ok, okClickListener).setNegativeButton(R.string.cancel, null).create()
                .show();

    }

    /**
     * 值监听
     */
    private View.OnClickListener resultOnClickListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            index = (Integer) v.getTag();
            Detection detection = array.get(index);

            // 二选一
            if ((detection.getValueType() & Detection.TYPE_TWO_SELECT) != 0) {
                showAlertSingleChoiceDialog(detection, singleChoiceListener);
                // 三选一
            } else if ((detection.getValueType() & Detection.TYPE_THREE_SELECT) != 0) {
                showAlertSingleChoiceDialog(detection, singleChoiceListener);

                // 多选一
            } else if ((detection.getValueType() & Detection.TYPE_SINGLE_CHOICE) != 0) {
                showAlertSingleChoiceDialog(detection, singleChoiceListener);

                // 多选
            } else if ((detection.getValueType() & Detection.TYPE_MULTIPLE) != 0) {
                showAlertMultipleChoiceDialog(detection, multipleChoiceListener);

            }

        }
    };

    /**
     * 设置值
     *
     * @param tv
     */
    private void setResult(Detection detection, TextView tv) {
        // 二选一
        if ((detection.getValueType() & Detection.TYPE_TWO_SELECT) != 0
                || (detection.getValueType() & Detection.TYPE_SINGLE_CHOICE) != 0) {
            String[] values = GlobalInfo.resources.getStringArray(detection.getResId());
            tv.setText(values[detection.getValue()]);
            if (detection.getValue() == 0) {// 正常
                tv.setBackgroundResource(R.color.deep_green);
                tv.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.ic_blue_yes, 0, R.mipmap.ic_drop_arrow, 0);
            } else {
                tv.setBackgroundResource(R.color.deep_red);
                tv.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.ic_red_cross, 0, R.mipmap.ic_drop_arrow, 0);
            }

            // 三选一
        } else if ((detection.getValueType() & Detection.TYPE_THREE_SELECT) != 0) {
            String[] values = GlobalInfo.resources.getStringArray(detection.getResId());
            tv.setText(values[detection.getValue()]);
            if (detection.getValue() == 0 || "无".equals(values[detection.getValue()])) {// 正常
                tv.setBackgroundResource(R.color.deep_green);
                tv.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.ic_blue_yes, 0, R.mipmap.ic_drop_arrow, 0);
            } else {
                tv.setBackgroundResource(R.color.deep_red);
                tv.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.ic_red_cross, 0, R.mipmap.ic_drop_arrow, 0);
            }

            // 多选
        } else if ((detection.getValueType() & Detection.TYPE_MULTIPLE) != 0) {
            String[] values = GlobalInfo.resources.getStringArray(detection.getResId());

            ArrayList<Integer> ints = detection.getValues();

            if (ints == null)
                ints = new ArrayList<Integer>();

            // 若为空值，默认为0
            if (ints.size() == 0)
                ints.add(0);

            String value = "";
            for (int i : ints) {
                if (TextUtils.isEmpty(value))
                    value = values[i];
                else
                    value += " " + values[i];
            }
            tv.setText(value);

            if (multipleValueOnlyRadio(values[ints.get(0)])) {// 正常
                tv.setBackgroundResource(R.color.deep_green);
                tv.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.ic_blue_yes, 0, R.mipmap.ic_drop_arrow, 0);
            } else {
                tv.setBackgroundResource(R.color.deep_red);
                tv.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.ic_red_cross, 0, R.mipmap.ic_drop_arrow, 0);
            }

            // 输入框
        } else if ((detection.getValueType() & Detection.TYPE_INPUT) != 0) {

        }

        if (detection.isRequestFocus()) {
            tv.setOnClickListener(resultOnClickListener);
        }
    }

    class HeaderViewHolder {
        TextView header;
        TextView result;
    }

    @Override
    public View getHeaderView(int position, View convertView, ViewGroup parent) {
        HeaderViewHolder viewHolder;
        if (convertView == null) {
            viewHolder = new HeaderViewHolder();
            convertView = inflater.inflate(R.layout.item_detection_subject, null);
            convertView.setTag(viewHolder);
            viewHolder.header = (TextView) convertView.findViewById(R.id.detection_subject_name_tv);
            viewHolder.result = (TextView) convertView.findViewById(R.id.skeleton_subject_result_tv);
            // viewHolder.result.setMinWidth(resultTvWidth);
        } else {
            viewHolder = (HeaderViewHolder) convertView.getTag();
        }
        Detection detection = array.get(position);
        viewHolder.header.setText(detection.getHeader());

        return convertView;
    }

    @Override
    public long getHeaderId(int position) {
        return array.get(position).getHeader().hashCode();
    }

    public void setResultTvWidth(int resultTvWidth) {
        this.resultTvWidth = resultTvWidth;
    }
}
